package com.zkzx.company.api.controller.driver;

import com.alibaba.fastjson.JSON;
import com.zkzx.common.company.model.CompanyDriverVO;
import com.zkzx.common.company.model.CompanyVO;
import com.zkzx.common.driver.command.DriverCommand;
import com.zkzx.common.driver.constants.DriverStatusEnum;
import com.zkzx.common.driver.model.DriverBankVO;
import com.zkzx.common.driver.model.DriverListVO;
import com.zkzx.common.driver.model.DriverVO;
import com.zkzx.common.driver.param.DriverFilterParam;
import com.zkzx.common.driver.param.VerificationParam;
import com.zkzx.common.driver.vo.DriverStatusVO;
import com.zkzx.common.exception.BaseException;
import com.zkzx.common.exception.ExceptionEnum;
import com.zkzx.common.global.Global;
import com.zkzx.common.sms.constants.SmsTemplateEnum;
import com.zkzx.common.truck.model.TruckVO;
import com.zkzx.common.vo.PageResult;
import com.zkzx.common.vo.RequestFilterParams;
import com.zkzx.common.vo.StatusVO;
import com.zkzx.company.api.client.company.CompanyClient;
import com.zkzx.company.api.client.driver.DriverClient;
import com.zkzx.company.api.client.truck.TruckClient;
import com.zkzx.company.api.controller.BaseController;
import com.zkzx.company.api.service.driver.DriverService;
import com.zkzx.util.data.HideDataUtil;
import com.zkzx.util.date.DateUtil;
import com.zkzx.util.json.JSONResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.util.StringUtils;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 北京中科智兴物联科技有限公司 @版权所有
 *
 * @Author: zhaoyihe@zkraising.com
 * @Date: 2021/05/08/16:01
 * @Description:
 */
@RestController
@Validated
@Api(tags="司机管理")
@RequestMapping(value = "/drivers")
public class DriverController extends BaseController {

    @Autowired
    private DriverClient driverClient;

    @Autowired
    private CompanyClient companyClient;

    @Autowired
    private DriverService driverService;

    @Autowired
    private TruckClient truckClient;

    @GetMapping
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "获取 司机列表", notes = "获取 司机列表")
    public PageResult<DriverListVO> find(@ApiParam(value = "查询参数") DriverFilterParam  filterParam,
                                         @ApiParam(value = "分页查询参数") RequestFilterParams params) {
        if(Objects.isNull(filterParam)){
            filterParam = new DriverFilterParam();
        }
        filterParam.setCompanyId(super.getCompanyId());

        PageResult<CompanyDriverVO> result = companyClient.findCompanyDriver(JSONResultUtil.object2JSON(filterParam),
                JSONResultUtil.object2JSON(params));

        return buildListVO(params,result);
    }

    @GetMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "获取司机详细", notes = "获取司机详细")
    public DriverVO getById(@PathVariable("id") Integer id) {
        return driverService.getById(id,super.getCompanyId(),super.getUserId());
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    @ApiOperation(value = "新增司机信息", notes = "新增司机信息")
    public StatusVO add(@RequestBody @Valid DriverCommand command) {

        CompanyVO companyVO = companyClient.getById(super.getCompanyId());
        if(StringUtils.isEmpty(companyVO.getThreeId())){
            throw new BaseException(ExceptionEnum.COMPANY_MEMBER_REVIEW_ERROR.getCode(),ExceptionEnum.COMPANY_MEMBER_REVIEW_ERROR.getMsg());
        }

        command.setCompanyId(super.getCompanyId());
        StatusVO statusVO = driverClient.add(command, super.getUserId());

        DriverVO driverVO = this.getById(statusVO.getId());
        //更新中间表
        CompanyDriverVO companyDriverVO = new CompanyDriverVO();
        companyDriverVO.setCompanyId(super.getCompanyId());
        companyDriverVO.setDriverId(statusVO.getId());
        companyDriverVO.setMobile(driverVO.getMobile());
        companyDriverVO.setDriverName(driverVO.getName());
        companyDriverVO.setDriverStatus(statusVO.getValue());
        companyDriverVO.setDriverSource(driverVO.getSource());
        companyClient.update(companyDriverVO);
        //网货存在且审核通过，并已同步到收单系统
        if (DriverStatusEnum.VERIFY_SUCCESS.name().equals(driverVO.getStatusVO().getValue())){
            this.sendDriverSms(driverVO.getStatusVO().getValue(),companyVO.getMemberMobile(),companyVO.getName(),driverVO.getName());
        }

        return statusVO;
    }

    @PutMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "修改司机信息", notes = "修改司机信息")
    public void update(@PathVariable("id") Integer id,@RequestBody @Valid DriverCommand command) {
        command.setCompanyId(super.getCompanyId());
        driverClient.update(command,id,super.getUserId());
    }

    @PostMapping("/{id}/verification")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "获取验证码", notes = "获取验证码")
    public DriverStatusVO verification(@PathVariable("id")Integer id) {

        return driverClient.verification(id,super.getUserId(),super.getCompanyId());
    }

    @PostMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "提交", notes = "提交")
    public DriverStatusVO submit(@PathVariable("id")Integer id, @RequestBody @Valid VerificationParam verificationParam)  {
        DriverStatusVO driverStatusVO = driverClient.submit(id, verificationParam.getCaptcha(), super.getUserId(), super.getCompanyId());
        //网货存在,审核通过或审核不通过
        if (DriverStatusEnum.VERIFY_SUCCESS.name().equals(driverStatusVO.getValue())
                || DriverStatusEnum.APPROVE_FAIL.name().equals(driverStatusVO.getValue())
                || DriverStatusEnum.BANK_FAIL.name().equals(driverStatusVO.getValue())){
            CompanyVO companyVO = companyClient.getById(super.getCompanyId());
            DriverVO driverVO = driverClient.getById(id, super.getCompanyId());
            this.sendDriverSms(driverStatusVO.getValue(),companyVO.getMemberMobile(),companyVO.getName(),driverVO.getName());
        }

        return  driverStatusVO;
    }

    @PostMapping("/{id}/contract")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "邀请签约", notes = "邀请签约")
    public DriverStatusVO contract(@PathVariable("id")Integer id)  {

        return driverClient.contract(id,Global.TWO_THOUSAND_AND_NINETY_NINE_YYYYMMDD_HHMMSS, super.getUserId(), super.getCompanyId());
    }


    @GetMapping("/list")
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "获取司机下拉框列表", notes = "获取司机下拉框列表")
    public List<CompanyDriverVO> findAll() {
        return companyClient.getByDriverIdAndCompanyId(Global.ZERO,super.getCompanyId());
    }


    /**
     * 封装查询页面分页vo
     * @param params 分页信息
     * @param result 返回集合
     * @return 页面分页集合
     */
    private PageResult<DriverListVO> buildListVO( RequestFilterParams params, PageResult<CompanyDriverVO> result){
        if (CollectionUtils.isEmpty(result.getResult())){
            return new PageResult<>(params.getPage(),params.getPerPage(),null, Global.ZERO);
        }

        List<DriverListVO> vos =  result.getResult().stream().map(companyDriverVO -> {
            DriverVO vo = driverClient.getById(companyDriverVO.getDriverId(),companyDriverVO.getCompanyId());

            DriverBankVO driverBank=new DriverBankVO();
            if (Objects.nonNull(vo.getDriverBank())){
                driverBank = vo.getDriverBank();
                driverBank.setCardNumber(HideDataUtil.getHideData(driverBank.getCardNumber()));
                driverBank.setMobile(HideDataUtil.getHideData(driverBank.getMobile()));
            }

            if (!StringUtils.isEmpty(companyDriverVO.getTruckId())){
                TruckVO truckVO = truckClient.getById(companyDriverVO.getTruckId(), super.getCompanyId(), super.getUserId());
                if(Objects.nonNull(truckVO)){
                    vo.setTruck(truckVO.getHeaderLicenseVO().getLicence());
                }

            }

            return DriverListVO.builder()
                    .id(vo.getId())
                    .cid(vo.getCid())
                    .name(vo.getName())
                    .identification(HideDataUtil.getHideData(vo.getIdentification()))
                    .truck(vo.getTruck())
                    .driverBank(driverBank)
                    .relationNumber(vo.getRelationNumber())
                    .createTime(DateUtil.convertDateToString(vo.getCreateTime()))
                    .source(companyDriverVO.getDriverSource())
                    .status(vo.getStatusVO())
                    .mobile(vo.getMobile())
                    .build();
        }).collect(Collectors.toList());


        return new PageResult<>(params.getPage(),params.getPerPage(),vos, result.getTotalNum());
    }

    /**
     * 司机审核短信通知
     * @param status  司机状态
     * @param mobile 公司联系人手机号
     * @param companyName 公司名称
     * @param driverName 车牌号
     */
    public void sendDriverSms(String status,String mobile,String companyName,String driverName){
        Map<String, String> parameterMap = new HashMap<>();
        //审核成功、审核失败、绑卡失败传参一致
        parameterMap.put(SmsTemplateEnum.DRIVER_EXAMINE_SUCCESS.getParameterArr()[Global.ZERO],companyName);
        parameterMap.put(SmsTemplateEnum.DRIVER_EXAMINE_SUCCESS.getParameterArr()[Global.ONE],driverName);
        if (DriverStatusEnum.VERIFY_SUCCESS.name().equals(status)){
            //已验证
            companyClient.sendSms(mobile, SmsTemplateEnum.DRIVER_EXAMINE_SUCCESS.getTemplate(), JSON.toJSONString(parameterMap));
        }else if (DriverStatusEnum.APPROVE_FAIL.name().equals(status)){
            //审核驳回
            companyClient.sendSms(mobile, SmsTemplateEnum.DRIVER_EXAMINE_FAIL.getTemplate(), JSON.toJSONString(parameterMap));
        }else if (DriverStatusEnum.BANK_FAIL.name().equals(status)){
            //绑卡失败
            companyClient.sendSms(mobile, SmsTemplateEnum.DRIVER_CARD_FAIL.getTemplate(), JSON.toJSONString(parameterMap));
        }
    }
}
